/**
 * 用户行为分析统计路由
 */
const Router = require('koa-router');
const router = new Router({
  prefix: '/stats'
});
const db = require('../../db');

// 获取埋点数据统计信息（不再需要验证）
router.get('/overview', async (ctx) => {
  try {
    // 获取事件类型统计
    const eventTypeCounts = await db.executeQuery(
      `SELECT event_type, COUNT(*) as count 
       FROM user_behaviors 
       GROUP BY event_type 
       ORDER BY count DESC`
    );
    
    // 获取每日事件统计
    const dailyEvents = await db.executeQuery(
      `SELECT 
         DATE(timestamp) as date, 
         COUNT(*) as count 
       FROM user_behaviors 
       WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
       GROUP BY DATE(timestamp) 
       ORDER BY date`
    );
    
    // 获取最活跃用户
    const activeUsers = await db.executeQuery(
      `SELECT 
         user_id, 
         COUNT(*) as event_count 
       FROM user_behaviors 
       GROUP BY user_id 
       ORDER BY event_count DESC 
       LIMIT 10`
    );
    
    // 获取最受关注的课程
    const popularCourses = await db.executeQuery(
      `SELECT 
         b.course_id, 
         c.title,
         COUNT(*) as event_count 
       FROM user_behaviors b
       JOIN courses c ON b.course_id = c.id
       WHERE b.course_id IS NOT NULL
       GROUP BY b.course_id
       ORDER BY event_count DESC
       LIMIT 10`
    );
    
    ctx.body = {
      code: 200,
      message: '统计数据获取成功',
      data: {
        eventTypeCounts,
        dailyEvents,
        activeUsers,
        popularCourses
      }
    };
  } catch (err) {
    console.error('获取埋点统计数据失败:', err);
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      error: err.message
    };
  }
});

// 获取特定用户的行为数据
router.get('/user/:userId', async (ctx) => {
  try {
    const userId = ctx.params.userId;
    const { limit = 100 } = ctx.query;
    
    // 获取用户行为数据
    const behaviors = await db.executeQuery(
      `SELECT * FROM user_behaviors 
       WHERE user_id = ? 
       ORDER BY timestamp DESC 
       LIMIT ?`,
      [userId, Math.min(parseInt(limit), 500)]
    );
    
    // 解析JSON字符串为对象
    const data = behaviors.map(row => ({
      ...row,
      extra_data: row.extra_data ? JSON.parse(row.extra_data) : null,
      device_info: row.device_info ? JSON.parse(row.device_info) : null
    }));
    
    ctx.body = {
      code: 200,
      message: '获取用户行为数据成功',
      data
    };
  } catch (err) {
    console.error('获取用户行为数据失败:', err);
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      error: err.message
    };
  }
});

// 获取课程相关事件统计
router.get('/course/:courseId', async (ctx) => {
  try {
    const courseId = ctx.params.courseId;
    
    // 获取课程事件统计
    const eventStats = await db.executeQuery(
      `SELECT 
         event_type, 
         COUNT(*) as count 
       FROM user_behaviors 
       WHERE course_id = ? 
       GROUP BY event_type`,
      [courseId]
    );
    
    // 获取每日事件统计
    const dailyStats = await db.executeQuery(
      `SELECT 
         DATE(timestamp) as date, 
         event_type,
         COUNT(*) as count 
       FROM user_behaviors 
       WHERE course_id = ? AND timestamp >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
       GROUP BY DATE(timestamp), event_type
       ORDER BY date`,
      [courseId]
    );
    
    ctx.body = {
      code: 200,
      message: '获取课程事件统计成功',
      data: {
        eventStats,
        dailyStats
      }
    };
  } catch (err) {
    console.error('获取课程事件统计失败:', err);
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      error: err.message
    };
  }
});

module.exports = router; 